import { useAuthStore } from '@/store/auth';
import http from '@/utils/http'
import { EventSourcePolyfill } from 'event-source-polyfill';
import { storeToRefs } from 'pinia';

const authStore = useAuthStore()
const { globalParams, historyParams } = storeToRefs(authStore)
let eventSource: EventSourcePolyfill | null = null;
let reconnectTimeout: number = 0;

export interface SSEParams {
  clientId: string;
  dataType: string; // 0-区域，1-人员,2-视频，3-传感器,4-报警
  startTime: string;
  endTime: string;
  customerNo?: string;
  alarmSource?: string;
  alarmType?: string;
  areaId?: string;
  name?: string;
  pageNumber?: number;
  pageSize?: number;
  sensorName?: string;
  sensorStatus?: string;
  sensorType?: string;
  type?: string
}

const { setHistoryData, setHistoryParams } = useAuthStore()

export function createSSE () {
  if (eventSource) {
    return eventSource;
  } else {
    eventSource = new EventSourcePolyfill(VITE_APP_BASE_URL + '/api/sse/connect', {
      headers: {
        'X-Client-ID': globalParams.value.clientId,
        // 'Authorization': 'Bearer ' + localStorage.getItem('token')
      },
      withCredentials: true, // 跨域请求是否携带凭证
    });
    eventSource.onopen = function () {
      console.log('连接成功');
      reconnectTimeout = 0;
    };
    eventSource.onerror = function (error) {
      console.log('连接错误', error);
      eventSource.close(); // 关闭连接
      eventSource = null; // 重置 eventSource 变量

      reconnectTimeout++
      console.log('重连次数', reconnectTimeout);
      createSSE(); // 重新创建 SSE 连接
    }

    eventSource.addEventListener('message', function (event) {
      console.log(JSON.parse(event.data));
      setHistoryData(JSON.parse(event.data))
    })

    return eventSource;
  }
}

export function closeSSE () {
  if (eventSource) {
    eventSource.close(); // 关闭连接
    eventSource = null; // 重置 eventSource 变量
  }
}

export function sseQuery (params: SSEParams) {
  const oparams = {
    ...params,
    customerNo: globalParams.value.customerNo,
    areaId: globalParams.value.areaId
  }
  setHistoryParams({
    startTime: params.startTime,
    endTime: params.endTime,
  })
  return http.postOrJson('/api/sse/process', oparams)
}